package com.github.springbootredis.repository;

import com.github.springbootredis.entity.Book;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Repository;

import java.util.List;
import java.util.Set;

/**
 *  redis作为数据库的操作类
 */
@Repository
public class BooksRepository {

    private final String prefix="book:";
    private final RedisTemplate<String, Book> redisTemplate;

    public BooksRepository(RedisTemplate<String, Book> redisTemplate) {
        this.redisTemplate = redisTemplate;
    }

    public void save(Book book) {
        redisTemplate.opsForValue()
                .set(prefix+book.getId(), book);
    }

    public Book findById(Long id) {
        return redisTemplate.opsForValue()
                .get(prefix+id);
    }

    public List<Book> findAll(){
        Set<String> ids=redisTemplate.keys(prefix+"*");
        return redisTemplate.opsForValue().multiGet(ids);
    }

    public void deleteAll(){
        Set<String> keys = redisTemplate.keys("*");
        redisTemplate.delete(keys);
    }

}
